package br.unicamp.ic.inf300.arena.persistencia.dao.impl;

import br.unicamp.ic.inf300.arena.modelo.vendas.Estorno;
import br.unicamp.ic.inf300.arena.modelo.vendas.EstornoCartao;
import br.unicamp.ic.inf300.arena.persistencia.dao.IEstornoDAO;
import br.unicamp.ic.inf300.framework.persistencia.SQLUtil;

public class EstornoDAOHsql implements IEstornoDAO {

	public long estornarBilhetes(Estorno estorno) throws Exception {
		StringBuffer stbQuery = new StringBuffer();
		stbQuery.append("INSERT INTO ");
		stbQuery.append(/*SQLUtil.getDbSchema() + "." +*/ IEstornoDAO.TABELA_BD + " (");
		stbQuery.append(IEstornoDAO.COLUMN_DTTHORA      + ", ");
		stbQuery.append(IEstornoDAO.COLUMN_VALOR        + ", ");
		stbQuery.append(IEstornoDAO.COLUMN_NUMCARTAO    + ", ");
		stbQuery.append(IEstornoDAO.COLUMN_BANDEIRA     + ", ");
		stbQuery.append(IEstornoDAO.COLUMN_NUMPROTOCOLO + ") ");
		stbQuery.append(" VALUES (?, ?, ?, ?, ?) ");
		Object[] params = new Object[5];
		if(estorno instanceof EstornoCartao){
			params[0] = estorno.getDataHora();
			params[1] = estorno.getVenda().getPagamento().getValor();
			params[2] = ((EstornoCartao)estorno).getCartaoCredito().getNumeroCartao();
			params[3] = ((EstornoCartao)estorno).getCartaoCredito().getBandeira();
			params[4] = estorno.getVenda().getNumProtocolo(); 
		} else {
			params[0] = estorno.getDataHora();
			params[1] = estorno.getVenda().getPagamento().getValor();
			params[2] = ""; 
			params[3] = "";
			params[4] = estorno.getVenda().getNumProtocolo();
		}
		
		boolean update = SQLUtil.update(stbQuery.toString(), params) > 0 ? true : false;
		long codigoEstorno = 0;
		if(update){
			StringBuffer stbSelect = new StringBuffer();
			stbSelect.append("SELECT MAX(" + IEstornoDAO.COLUMN_CODIGO_PK + ") ");
			stbSelect.append("FROM " + IEstornoDAO.TABELA_BD);
			codigoEstorno = ((Long)SQLUtil.selectARecord(stbSelect.toString(), null)).longValue();
		}
		return codigoEstorno;
		
	}

}
